var express = require("express");
var router = express.Router();

//引入连接数据库模块
const conn = require("../conn");

//连接数据
conn.connect(() => {});
var jsonWrite = function(res, ret) {
    if (typeof ret === "undefined") {
        res.json({
            code: "1",
            msg: "操作失败",
        });
    } else {
        res.json(ret);
    }
};

//新增评价
router.post("/insertComments", function(req, res) {
    const sqlStr =
        "insert into comments(content,product_id,userId,commentTime) values (?,?,?,?)";
    var params = req.body;
    conn.query(
        sqlStr, [params.content, params.product_id, params.userId, params.commentTime],
        (err, result) => {
            if (err) {
                throw err;
            }
            if (result) {
                jsonWrite(res, result);
            }
        }
    );
});
//查询评价
router.post("/selComments", function(req, res) {
    let { userId, product_id } = req.body;
    const sqlStr = `select * from 
    comments LEFT JOIN users ON comments.userId=users.userId
    where  comments.product_id='${product_id}'`;
    conn.query(sqlStr, (err, result) => {
        if (err) {
            throw err;
        }
        if (result) {
            jsonWrite(res, result);
        }
    });
});

module.exports = router;